package model

import (
	"common/helper"
	"database/sql"
	"fmt"
	"github.com/valyala/fasthttp"
	"strconv"
	"strings"
	"time"
)

// 游戏投注记录结构
type CoinRecordData struct {
	AfterAmount  string `db:"after_amount" json:"after_amount" cbor:"after_amount"`    //账变后的金额
	Amount       string `db:"amount" json:"amount" cbor:"amount"`                      //用户填写的转换金额
	BeforeAmount string `db:"before_amount" json:"before_amount" cbor:"before_amount"` //账变前的金额
	BillNo       string `db:"bill_no" json:"bill_no" cbor:"bill_no"`                   //转账|充值|提现ID
	CashType     int    `db:"cash_type" json:"cash_type" cbor:"cash_type"`             //0:转入1:转出2:转入失败补回3:转出失败扣除4:存款5:提现
	CreatedAt    int64  `db:"created_at" json:"created_at" cbor:"created_at"`          //
	ID           string `db:"id" json:"id" cbor:"id"`                                  //
	UID          string `db:"uid" json:"uid" cbor:"uid"`                               //用户ID
	CashName     string `db:"cash_name" json:"cash_name" cbor:"cash_name"`
	GameTax      string `db:"game_tax" json:"game_tax" cbor:"game_tax"` //账变前的金额
	GameId       string `db:"game_id" json:"game_id" cbor:"game_id"`    //
	PlatformId   string `db:"platform_id" json:"platform_id" cbor:"platform_id"`
	PlatformName string `json:"platform_name" db:"platform_name"`
	RouteName    string `json:"route_name" db:"route_name"`
	Username     string `db:"username" json:"username" cbor:"username"` //用户名
	BusinessId   string `json:"business_id" db:"business_id"`           // 业务员id
	OperatorId   string `json:"operator_id" db:"operator_id"`           // 渠道id
	OperatorName string `json:"operator_name" db:"operator_name"`       // 渠道账号
	BusinessName string `json:"business_name" db:"business_name"`       // 业务员账号

	Sandbag string `json:"sandbag" db:"sandbag"` // 业务员账号

}

// 游戏记录数据
type CoinRecordDataRet struct {
	T int64            `json:"total" cbor:"t"`
	D []CoinRecordData `json:"d" cbor:"d"`
}

type CoinRecordStatisticsData struct {
	Running     float64 `json:"running" db:"running"`           // 流水
	GameTax     float64 `json:"game_tax" db:"game_tax"`         // 游戏税收
	GameWinlost float64 `json:"game_winlost" db:"game_winlost"` // 游戏赢亏
}

func CoinRecord(param CoinListParam, ctx *fasthttp.RequestCtx) (CoinRecordDataRet, error) {
	data := CoinRecordDataRet{}

	where := "1=1"
	oderBy := "created_at"
	oderType := "desc"

	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLocMs(param.StartTime, loc)
		where += " and a.created_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLocMs(param.EndTime, loc)
		where += " and a.created_at<'" + strconv.FormatInt(EndTime, 10) + "'"
	}

	if param.Uid != "" {
		where += " and a.uid=" + param.Uid
	}
	if param.Ctype != "" {
		where += " and a.cash_type in(" + strings.Trim(param.Ctype, ",") + ")"
	}
	if param.OperatorId != "" {
		where += " and b.operator_id=" + param.OperatorId
	}
	if param.BusinessId != "" {
		where += " and b.business_id=" + param.BusinessId
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}
	order := oderBy + " " + oderType

	table := "tbl_balance_transaction"
	join := " left join tbl_member_base as   b on b.uid=a.uid" //玩家表
	//join += " left join tbl_transaction_types as     c on c.id=a.cash_type" //类型表
	//join += " left join tbl_operator_info as d on d.id=b.operator_id"       //渠道表
	//join += " left join tbl_business_info as e on e.id=b.business_id"       //业务员表

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.operator_id=" + loginUser.Operator
	} else if loginUser.Businsess != "" {
		where += " and b.business_id=" + loginUser.Businsess
	}

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		countJoin := join
		if loginUser.Admin != "" && param.OperatorId == "" && param.BusinessId == "" {
			countJoin = ""
		}
		count := "select count(1) from " + table + " as a " + countJoin + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*,b.username,b.business_id,b.operator_id"
	query := "select " + field + "  from " + table + " as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	fmt.Println(query)
	err := meta.MerchantDB.Select(&data.D, query)

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return data, nil
}

// 金币日志数据处理
func CoinRecordListOpt(data CoinRecordDataRet, exportExcel int) (CoinRecordDataRet, [][]interface{}) {
	exportData := [][]interface{}{}
	//获取变动类型
	transTypes, _ := GetTransTypes()
	transTypesList := map[string]string{}
	for _, value := range transTypes {
		transTypesList[value.ID] = value.Name
	}

	for key, value := range data.D {
		value.CashName = transTypesList[strconv.Itoa(value.CashType)]
		(data.D)[key].CashName = value.CashName
		if exportExcel == 1 {
			single := []interface{}{
				value.UID,
				value.OperatorId,
				value.PlatformId,
				value.BeforeAmount,
				value.CashName,
				value.Amount,
				value.AfterAmount,
				value.GameTax,
				time.UnixMilli(value.CreatedAt).Format("2006-01-02 15:04:05"),
			}
			exportData = append(exportData, single)
		}
	}
	return data, exportData
}
